package com.bicon.botu.finance.payment.service;

import com.alibaba.fastjson.JSONObject;
import com.bicon.botu.core.base.common.BusinessException;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.finance.payment.alipay.AliPayService;
import com.bicon.botu.finance.payment.common.PaymentConstants;
import com.bicon.botu.finance.payment.entity.AliPayDto;
import com.bicon.botu.finance.payment.entity.AppPaymentInfoEntity;
import com.bicon.botu.finance.payment.entity.UnionpayDto;
import com.bicon.botu.finance.payment.entity.WechatPayDto;
import com.bicon.botu.finance.payment.weixin.api.WeChatPayService;
import com.bicon.botu.finance.payment.weixin.utils.PayUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 退款
 * @author: jwj
 * @date: 10:58 2018/6/26/001
 */
@Service
@Log4j
public class RefundService implements IRefundService{

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private WeChatPayService weChatPayService;

    public BaseResult refund() {
        //获取app在支付宝平台的相关信息
        AliPayDto aliPayDto = new AliPayDto();
        aliPayDto.setAlipayAccount("botu@biconjs.com");
        aliPayDto.setAlipayAppId("2017071107714840");
        aliPayDto.setAlipayAppPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCKazs6MfyoxyMZ7H7EEoli5+4ZUsBTw9CRI7eEr7+q/jEwmVqCFk1bufMmc0WJ584sAb16KgQAHIszI0TyUsBgYa7iLBI19/I+BLR4Mb82ny8wjUeHS+/Aq/Mpf7/w6SUrCZ7yZiRpr5pfmPEoJYwSoVjh9fCUMGfcj5T7txWP2xHPf/b4p10WuOpcaBIMD3Irl1UCKZoyFaoKT4CSyHQ8bGp/MoxXfdSVmDDjZJ6jRO9QwAZFJ6fwas11H6/+ifAiCW3EkHhET0kKJdEAYOyc03obY2wLKmnSxFdDsAGHYqS0aSnTH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x14NXkB+ZsLOHCTTBAoGARJlus+3v/QwJiwZQcDkqRlAdv8g57vYHLENrC7lEB1JPaoD/kIbAdafNO0fakKC7XmBblowI+WrpcZI09toLQqNsFGAy2y8/2y3/qfUE8VZjP3JdKg9Y2mgdfDLgC3JkmiDqRubSY8PZbs3CLIg3zl1fZYklmxzywY7n7D/68OY=");
        aliPayDto.setAlipayAppPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAims7OjH8qMcjGex+xBKJYufuGVLAU8PQkSO3hK+/qv4xMJlaghZNW7nzJnNFiefOLAG9eioEAByLMyNE8lLAYGGu4iwSNffyPgS0eDG/Np8vMI1Hh0vvwKvzKX+/8OklKwme8mYkaa+aX5jxKCWMEqFY4fXwlDBn3I+U+7cVj9sRz3/2+KddFrjqXGgSDA9yK5dVAimaMhWqCk+Aksh0PGxqfzKMV33UlZgw42Seo0TvUMAGRSen8GrNdR+v/onwIgltxJB4RE9JCiXRAGDsnNN6G2NsCypp0sRXQ7ABh2KktGkp0x+mXWF8KTKANfHLT0u0Bd5J0K0xO1DDlrdUmQIDAQAB");
        aliPayDto.setAlipayPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlvRyNu9fTIyeV9zh2NUh07CvNQgGLUkm66mDac+h/S062fBFsU+Tqxk0/CWdMvKy3EEpUHcNGrWSl0bOJn1uuw98xqgKwZYCnk/7fEo44IVkbYQJ8Lqr4v3tTCXoxSav/3CWNKFyYoWkNSn1mq4lEpv3QvDS7hqXH3kdE15qnY/sTHpPA3UxArXB8QUamPeTg3QmlrsvG+c28Bw2aKwcM3OJRptAJXlB2ZhwQHpf5/TyWEFhtJSiwgAziEWWsGdBDqfnfDo2hwcC+OmlrPQRfjVQ5DUF1CWaDzju7Gz9i57Nivbqk8vs2FdbNZoLunt7pZzMQxerLMG7PSbxXPzIxQIDAQAB");
        aliPayDto.setPayerAccount("botu@biconjs.com");
        aliPayDto.setPayerName("伯图电子商务");
        String result = aliPayService.tradeRefund(aliPayDto.getAlipayAppId(), aliPayDto.getAlipayPublicKey(),
                aliPayDto.getAlipayAppPrivateKey(), "20180626164658903920488254", "0.01", "", "", "", "");
        log.info(result);
        return  new BaseResult(200,"", result);
    }


    /**
     * 申请退款
     *
     * @param infoEntity 应用code
     * @param type       支付类型 1:支付宝 2:微信 3:银联
     * @param orderNo    订单号
     * @param money      退款金额
     * @param refundNo   退款编号
     * @param orderMoney
     * @return
     */
    @Override
    public BaseResult refund(AppPaymentInfoEntity infoEntity, String type, String orderNo, String money, String refundNo, String refundReason, String orderMoney) {
        //金额参数校验
        float total = 0.0f;
        float orderAmount = 0.0F;
        try {
            total = Float.parseFloat(money);
            orderAmount = Float.parseFloat(orderMoney);
        } catch (Exception e) {
            log.info("error", e);
            return new BaseResult(PaymentConstants.RESPONSE_CODE_400, "金额异常", null);
        }
        String message = "";
        int resultCode = Constants.RESPONSE_CODE_200;
        if (type.equals(AliPayDto.TYPE_ALIPAY)) {
            //获取app在支付宝平台的相关信息
            AliPayDto aliPayDto = infoEntity.getAliPayDto();
            if (null == aliPayDto) {
                return new BaseResult(PaymentConstants.RESPONSE_CODE_400, "支付宝支付参数为空", null);
            }
            //预支付
            message = aliPayService.tradeRefund(aliPayDto.getAlipayAppId(), aliPayDto.getAlipayPublicKey(),
                    aliPayDto.getAlipayAppPrivateKey(), orderNo, money, refundNo, "", refundReason, "");
            JSONObject jsonObject = JSONObject.parseObject(message);
            String alipaycode = jsonObject.getJSONObject("alipay_trade_refund_response").getString("code");
            if (!alipaycode.equals(PaymentConstants.alipay_trade_refund_code)) {
                resultCode = Constants.RESPONSE_CODE_500;
            }
            log.info("调用支付宝返回：" + message);
        } else if (type.equals(WechatPayDto.TYPE_WECHAT)) {
            WechatPayDto wechatPay = infoEntity.getWechatPayDto();
            message = this.weChatPayService.refund(wechatPay.getWechatAppId(),wechatPay.getWechatAppPartner(),null,orderNo,
                    refundNo, new BigDecimal(orderMoney),new BigDecimal(money),refundReason,null,wechatPay.getWechatAppKey(),
                    wechatPay.getWechatAppCertPath(),wechatPay.getWechatAppPartner());
            log.info("调用微信退款返回：" + message);
            if(StringUtils.isBlank(message)){
                throw new BusinessException(Constants.RESPONSE_CODE_500,"调用微信支付发生异常：返回为空");
            }
            Map<String, String> resMp = PayUtils.decodeXml(message);
            if (!resMp.get("result_code").equals("SUCCESS")) {
                throw new BusinessException(Constants.RESPONSE_CODE_500,"调用微信支付发生异常："+resMp.get("err_code_des"));
            }
        } else if (type.equals(UnionpayDto.TYPE_UNION)) {
        } else {
            return new BaseResult(PaymentConstants.RESPONSE_CODE_400, PaymentConstants.RESPONSE_MESSAGE_400, null);
        }
        if (null != message) {
            return new BaseResult(resultCode, PaymentConstants.RESPONSE_MESSAGE_200, message);
        }
        return new BaseResult(200,"", message);
    }
}
